package info.wangyuan.agent.utils;

import info.wangyuan.agent.config.properties.JwtProperties;
import info.wangyuan.agent.exception.BusinessException;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT 工具类（基于 jjwt 0.9.1）
 */
@Component
public class JwtUtils {


    private final JwtProperties jwtProperties;

    public JwtUtils(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    private static final String JWT_TOKEN_KEY = "openid";

    /**
     * 生成 token
     */
    public String generateToken(String openId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(JWT_TOKEN_KEY, openId);

        long ttl = jwtProperties.getUserTtl();
        Date now = new Date();
        Date exp = new Date(now.getTime() + ttl);

        return Jwts.builder()
                .setClaims(claims)                    // 自定义 claims
                .setIssuedAt(now)                     // 签发时间（iat）
                .setExpiration(exp)                   // 过期时间（exp）
                .signWith(SignatureAlgorithm.HS256, jwtProperties.getUserSecretKey()) // 签名
                .compact();
    }

    /**
     * 从 token 中解析 openid
     */
    public String getOpenidFromToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(jwtProperties.getUserSecretKey())
                    .parseClaimsJws(token)
                    .getBody();
            return (String) claims.get(JWT_TOKEN_KEY);
        } catch (ExpiredJwtException e) {
            throw new BusinessException("JWT token has expired", e);
        } catch (UnsupportedJwtException e) {
            throw new BusinessException("Unsupported JWT token", e);
        } catch (SignatureException e) {
            throw new BusinessException("Invalid JWT signature", e);
        } catch (IllegalArgumentException e) {
            throw new BusinessException("JWT token is empty", e);
        }
    }

    /**
     * 校验 token 是否有效
     */
    public boolean validateToken(String token) {
        try {
            Jwts.parser()
                    .setSigningKey(jwtProperties.getUserSecretKey())
                    .parseClaimsJws(token);
            return true;
        } catch (SignatureException e) {
            throw new BusinessException("Invalid JWT signature", e);
        } catch (ExpiredJwtException e) {
            throw new BusinessException("JWT token has expired", e);
        } catch (UnsupportedJwtException e) {
            throw new BusinessException("Unsupported JWT token", e);
        } catch (IllegalArgumentException e) {
            throw new BusinessException("JWT token is empty", e);
        }
    }
}
